package com.dhh.sky.activity;

import java.io.File;
import java.util.Arrays;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.devspark.appmsg.AppMsg;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.service.CameraUploadService;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Config;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.widget.CameraGridImageAdapter;
import com.dhh.sky.widget.SlideMenuFragment;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class CameraActivity extends SlidingFragmentActivity{
	private SharedPreferences spTemp;
	private LinearLayout initList;
	private LinearLayout photoGrid;
	private FileManager fm;
	private Context context;
	private ImageView image;
	private ProgressBar progress;
	private TextView status;
	private TextView initMessage;
	private GridView gridView;
	private CameraGridImageAdapter adapter;
	private final int TYPE_VIEW_START = 1;
	private final int TYPE_VIEW_NO_PHOTO = 2;
	private final int TYPE_VIEW_ERROR = 3;
	private final int TYPE_VIEW_INIT_PHOTO = 4;
	private String currentPath;
	protected UpdateReceiver updateReceiver = new UpdateReceiver();	
	protected IntentFilter updateFilter = new IntentFilter(Constant.SERVICE_NAME_CAMERA);
	protected MenuItem startAction;
	protected MenuItem stopAction;
	
	@Override 
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);		
		setBehindContentView(R.layout.menu_frame);
        setContentView(R.layout.camera_upload);       
        
        context = this;
        fm = new FileManager(this);        
		initList = (LinearLayout) this.findViewById(R.id.cp_init_list);      
		photoGrid = (LinearLayout) this.findViewById(R.id.camera_grid_view); 
		spTemp = getSharedPreferences(Constant.FOLDER_LOG_CAMERA_FOLDER_TEMP, 0);
        spTemp.edit().clear().commit();
        
        image = (ImageView) this.findViewById(R.id.cp_image);
        progress = (ProgressBar) this.findViewById(R.id.cp_progress);
        status = (TextView) this.findViewById(R.id.cp_status);
        initMessage = (TextView) this.findViewById(R.id.cp_init_msg);
        gridView = (GridView) this.findViewById(R.id.gridview);
        
        image.setOnClickListener(new View.OnClickListener(){			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context,CameraListActivity.class);
				startActivity(intent);				
			}
		});
        
        getSupportFragmentManager().beginTransaction()
			.replace(R.id.menu_frame, new SlideMenuFragment()).commit();
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        
        initActionBar();
        showInitView(true);        
        preparePhoto();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		registerReceiver(updateReceiver, updateFilter);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(updateReceiver);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
		startAction = menu.add(getString(R.string.ab_upload));
		startAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		startAction.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item){
				Intent intent = new Intent(context,CameraUploadService.class);
				context.startService(intent);
				showStartView();
				startAction.setVisible(false);
				stopAction.setVisible(true);
				return true;
			}
		});
		startAction.setEnabled(false);
		
		stopAction = menu.add(getString(R.string.label_stop));
		stopAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		stopAction.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item){
				CameraUploadService.isStop = true;
				showDoneView();
				return true;
			}
		});
		stopAction.setVisible(false);
		
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
	        case android.R.id.home:     
	        	toggle();
				return true;
        }
    	
        return false;
    }
	
	private void initActionBar(){
		getSupportActionBar().setTitle(getString(R.string.title_camera_upload));
        getSupportActionBar().setHomeButtonEnabled(true);    
    	getSupportActionBar().setIcon(R.drawable.ic_app_menu);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);  		
	}
	
	
	public void showInitView(boolean isShow){
		if(isShow){
			initList.setVisibility(View.VISIBLE);
			initMessage.setText(this.getString(R.string.msg_initializing));
		}else{
			initList.setVisibility(View.GONE);
			photoGrid.setVisibility(View.GONE);
		}
		
		if(startAction!=null){
			startAction.setVisible(false);
		}
		
		if(stopAction!=null){
			stopAction.setVisible(false);
		}
	}
	
	private void preparePhoto(){
		new PreparePhotoTask().execute();
	}
	
	@Override 
	public void onStart(){
		super.onStart();
	}
	
	public class PreparePhotoTask extends AsyncTask<Void, Void, Boolean>{
		@Override
		protected Boolean doInBackground(Void... arg0) {
			ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
			final SDAApplication app = ((SDAApplication) getApplication());
			if(activeNetwork==null || !activeNetwork.isConnected()) {				
				sendToast(getString(R.string.msg_error_network));
				showDoneView();
				return false;
			}else{
				LiveConnectClient mClient = app.getConnectClient();
				if(mClient==null){
					final LiveAuthClient aClient = new LiveAuthClient(context,Config.CLIENT_ID);
					aClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener(){
			            @Override
			            public void onAuthError(LiveAuthException exception, Object userState) {
			            	sendToast(context.getString(R.string.msg_error_network));
			            	showDoneView();
			            }

			            @Override
			            public void onAuthComplete(LiveStatus status,LiveConnectSession session,Object userState) {
			                if (status==LiveStatus.CONNECTED) {
			                	app.setAuthClient(aClient);
			                	app.setSession(session);
			                	LiveConnectClient conn = new LiveConnectClient(session);
			                    app.setConnectClient(conn);
			                    preparePhoto();
			                }else{
				            	sendToast(context.getString(R.string.msg_error_connect));
				            	showDoneView();
			                }
			            }
			        });
				}else{
					LiveConnectClient conn = app.getConnectClient();
					String path = null;
					fm.syncFiles(conn, Constant.SKYFRIVE_PATH_HOME);
					SkyDriveObject folder = fm.getFileByName(Constant.CAMERA_UPLOAD_FOLDER,Constant.SKYFRIVE_PATH_HOME);
					if(folder!=null){
						path = folder.getId();
						if(fm.needSync(path)){
							fm.syncFiles(conn, path);
						}
					}else if(fm.createCameraUploadFolder(conn)){
						path = fm.getFileByName(Constant.CAMERA_UPLOAD_FOLDER,Constant.SKYFRIVE_PATH_HOME).getId();
					}else{
						Message msg = CUtil.buildMessage();
						msg.getData().putInt(Constant.PARAM_ID, TYPE_VIEW_ERROR);
						showViewHandler.sendMessage(msg);
						return false;
					}
					
					fm.initUploadPhotos(conn, path);					
					Message msg = CUtil.buildMessage();
					msg.getData().putInt(Constant.PARAM_ID, TYPE_VIEW_INIT_PHOTO);
					showViewHandler.sendMessage(msg);
				}
			}
			return true;
		}
		
	}
	
	private void showStartView(){				
		if(spTemp.getAll().size()==0){
			showNoPhotoView();
		}else{
			initList.setVisibility(View.GONE);
			photoGrid.setVisibility(View.GONE);
			//image.setImageBitmap(CUtil.decodeBitmap(file, 200, 300));
			status.setVisibility(View.GONE);
			progress.setVisibility(View.GONE);
		}	
	}
	
	private void showInitPhotos(){
		adapter = new CameraGridImageAdapter(this);
		gridView.setAdapter(adapter);	
		photoGrid.setVisibility(View.VISIBLE);
		initList.setVisibility(View.GONE);
		startAction.setEnabled(true);
	}
		
	private void showNoPhotoView(){
		initList.setVisibility(View.VISIBLE);
		photoGrid.setVisibility(View.GONE);
		initMessage.setText(this.getString(R.string.msg_no_photo));	
		showAction(false,false);	
	}
	
	private void showErrorView(String message){
		initList.setVisibility(View.VISIBLE);
		photoGrid.setVisibility(View.GONE);
		initMessage.setText(this.getString(R.string.msg_no_photo));	
		showAction(false,false);		
	}	
	
	private void showDoneView(){
		initList.setVisibility(View.VISIBLE);
		photoGrid.setVisibility(View.GONE);
		initMessage.setText(this.getString(R.string.msg_done));	
		showAction(false,false);		
	}
	
	private void showAction(boolean isShowStart,boolean isShowStop){
		startAction.setVisible(isShowStart);
		stopAction.setVisible(isShowStop);
	}
	
	private void updateProgress(int current,int max,String path){
		if(path!=null && !path.equalsIgnoreCase(currentPath)){
			currentPath = path;
			File file = new File(path);
			if(file.exists())
				image.setImageBitmap(CUtil.decodeBitmap(file, 200, 300));
		}
		progress.setVisibility(View.VISIBLE);
		progress.setMax(max);
		progress.setProgress(current);
		status.setVisibility(View.VISIBLE);
		status.setText(context.getString(R.string.msg_uploading)+"  "+current+"/"+max);
		
		if(current==max){
			showDoneView();
		}
	}
	
	public void sendToast(String message){
    	Bundle data = new Bundle();
		data.putString(Constant.PARAM_MESSAGE, message);
		Message msg = new Message();
		msg.setData(data);
		msgHandler.sendMessage(msg);
    }
	
	protected Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		String text = msg.getData().getString(Constant.PARAM_MESSAGE);
    		CUtil.showToast(CameraActivity.this, text, AppMsg.STYLE_ALERT);
        }
    };
    
    private Handler showViewHandler = new Handler() {
		@Override
        public void handleMessage(Message msg){
			Bundle data = msg.getData();
			int type = data.getInt(Constant.PARAM_ID);
			if(TYPE_VIEW_START == type){
				showStartView();
			}else if(TYPE_VIEW_NO_PHOTO == type){
				showNoPhotoView();
			}else if(TYPE_VIEW_ERROR == type){
				showErrorView(data.getString(Constant.PARAM_MESSAGE));
			}else if(TYPE_VIEW_INIT_PHOTO == type){
				showInitPhotos();
			}
		}
    };
    
    private Handler updateHandler = new Handler() {
		@Override
        public void handleMessage(Message msg) { 
			int max = msg.getData().getInt(Constant.PARAM_MAX);
	    	int current = msg.getData().getInt(Constant.PARAM_PROGRESS);
	    	String path = msg.getData().getString(Constant.PARAM_ITEM_NAME);
	    	String message = msg.getData().getString(Constant.PARAM_MESSAGE);
	    	boolean isFailed = msg.getData().getBoolean(Constant.PARAM_DONE);
	    	
	    	if(isFailed){
	    		CUtil.showToast(CameraActivity.this, getString(R.string.msg_error_upload_photo)+" "+message, AppMsg.STYLE_ALERT);
	    	}
	    	
	    	updateProgress(current,max,path);
		}
    };
    
    private class UpdateReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	int max = intent.getExtras().getInt(Constant.PARAM_MAX);
	    	int current = intent.getExtras().getInt(Constant.PARAM_PROGRESS);
	    	String path = intent.getExtras().getString(Constant.PARAM_ITEM_NAME);
	    	String message = intent.getExtras().getString(Constant.PARAM_MESSAGE);
	    	boolean isFailed = intent.getExtras().getBoolean(Constant.PARAM_DONE);
	    	
	    	Message msg = updateHandler.obtainMessage();
	    	Bundle data = new Bundle();
	    	data.putInt(Constant.PARAM_MAX, max);
	    	data.putInt(Constant.PARAM_PROGRESS, current);
	    	data.putString(Constant.PARAM_MESSAGE, message);
	    	data.putString(Constant.PARAM_ITEM_NAME, path);
	    	data.putBoolean(Constant.PARAM_DONE, isFailed);
	    	msg.setData(data);
	    	updateHandler.sendMessage(msg);
	    }
	}

}
























